package org.fujay.langchain4jserver.interfaces.api;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fujay.commons.core.result.R;
import org.fujay.langchain4jserver.application.command.CreateApplicationCommand;
import org.fujay.langchain4jserver.application.command.UpdateApplicationConfigurationCommand;
import org.fujay.langchain4jserver.application.dto.ApplicationDetailDTO;
import org.fujay.langchain4jserver.application.dto.ApplicationSummaryDTO;
import org.fujay.langchain4jserver.application.service.ApplicationService;
import org.fujay.langchain4jserver.domain.application.vo.AppId;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.NoSuchElementException;

/**
 * 应用管理 API
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/applications")
@RequiredArgsConstructor
public class ApplicationController {

    private final ApplicationService applicationService;
    /**
     * 创建新应用
     */
    @PostMapping
    public R<ApplicationDetailDTO> createApplication(
            @Valid @RequestBody CreateApplicationCommand command) {

        ApplicationDetailDTO createdApp = applicationService.createApplication(command);

        return R.ok(createdApp);
    }

    /**
     * 获取应用列表（概要信息）
     */
    @GetMapping
    public R<List<ApplicationSummaryDTO>> listApplications() {
        return R.ok(applicationService.listApplications());
    }

    /**
     * 获取应用详情
     */
    @GetMapping("/{id}")
    public R<ApplicationDetailDTO> getApplicationDetail(@PathVariable Long id) {
        AppId appId = new AppId(id);
        ApplicationDetailDTO dto =
                applicationService
                        .getApplication(appId)
                        .orElseThrow(() -> new NoSuchElementException("应用不存在: " + id));
        return R.ok(dto);
    }

    /**
     * 更新应用信息与配置
     */
    @PutMapping
    public R<Void> updateApplication(
            @Valid @RequestBody UpdateApplicationConfigurationCommand command) {
        applicationService.updateApplicationConfiguration(command);
        return R.ok();
    }

    /**
     * 删除应用
     */
    @DeleteMapping("/{id}")
    public R<Void> deleteApplication(@PathVariable Long id) {
        AppId appId = new AppId(id);
        applicationService.deleteApplication(appId);
        return R.ok();
    }

    // TODO: Add endpoint for rollback?
}
